<template>
    <div style="width: 95%;margin: auto;">
        <el-button type="primary" :icon="Plus" @click="batchedDeleteByIds()">新增角色</el-button>
    </div>
    <!-- 全部角色表单 -->
    <div>
        <el-table :data="tableData.roles" style="width: 95%; margin: auto;">
            <el-table-column label="编号" prop="rid" width="250px" fixed />
            <el-table-column label="角色名" prop="rolename" width="250px" />
            <el-table-column label="备注" prop="remarks" width="250px" />
            <el-table-column width="address" fixed="right" label="操作">
                <template #default="scope">
                    <el-tooltip class="box-item" effect="dark" content="修改角色信息" placement="bottom">
                        <el-button type="primary" :icon="Edit" circle @click="handleEdit(scope.$index, scope.row)" />
                    </el-tooltip>
                    <el-tooltip class="box-item" effect="dark" content="删除" placement="bottom">
                        <el-button type="danger" :icon="Delete" circle @click="handleDelete(scope.row)" />
                    </el-tooltip>
                    <el-tooltip class="box-item" effect="dark" content="分配菜单" placement="bottom">
                        <el-button type="success" :icon="Setting" circle @click="updateRoleMenuBtn(scope.row)" />
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div>
        <!-- 修改或新增对话框 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="25%" draggable>
            <!-- 角色表单 -->
            <el-form :inline="true" :model="dialog.role" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="dialog.role.rolename" placeholder="请输入角色名" clearable
                        style="width: 200px;height: 35px;" />
                </el-form-item>
                <el-form-item>
                    <el-input v-model="dialog.role.remarks" placeholder="请输入备注" clearable
                        style="width: 200px;height: 35px;" />
                </el-form-item>
                <el-form-item style="margin-top: 20px;">
                    <el-button type="primary" @click="insertAndUpdateUser">{{ dialog.btnText }}</el-button>
                    <el-button type="primary" @click="clearFormData">清空</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
    <div>
        <!-- 更新角色菜单对话框 -->
        <el-dialog v-model="updateMenudialog.visible" :title="updateMenudialog.title" width="25%" draggable>
            <!-- data:树形结构的数据  show-checkbox：表示节点可操作 default-expanded-keys：表示设置默认展开的节点-->
            <!--node-key ： 表示唯一数值，使用后端主键  default-checked-keys：默认选中的节点 props：树形控件显示数据的结构-->
            <el-tree ref="menuTree" style="max-width: 600px" :data="updateMenudialog.menus" show-checkbox node-key="mid"
                :default-checked-keys=updateMenudialog.defaultKeys :props="defaultProps" />
            <el-button type="primary"   @click="updateRoleMenus()" style="margin-left: 250px;">确认修改</el-button>
        </el-dialog>
    </div>
</template>
<script setup>
//1.引入ref和reactive
import { ref, reactive, onMounted } from 'vue';
import request from '../utils/request';
import { Delete, Edit, Plus, Search, Setting } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

//通过ref获取指定的el-tree
const menuTree = ref();
//定义分配菜单按钮中树形控件的数据结构
const defaultProps = {
    children: 'children',
    label: 'mname',
}
//定义table数组，role数组
let tableData = reactive({
    roles: [],
});
//定义对话框属性
let dialog = ref({
    visible: false,
    title: '',
    btnText: '',
    role: {
        rid: '',
        rolename: '',
        remarks: '',
        menus: [],
    }
})
//显示修改角色对话框
const handleEdit = (index, row) => {
    //显示表单信息
    dialog.value.role.rid = row.rid;
    dialog.value.role.rolename = row.rolename;
    dialog.value.role.remarks = row.remarks;
    //设置对话框标题
    dialog.value.title = "修改角色";
    //设置按钮文本内容
    dialog.value.btnText = "更新数据";
    //显示对话框
    dialog.value.visible = true;
}
//显示新增角色对话框
const batchedDeleteByIds = () => {
    //设置对话框标题
    dialog.value.title = "新增角色";
    //设置按钮文本内容
    dialog.value.btnText = "提交";
    dialog.value.role.rid = '';
    dialog.value.role.rolename = "";
    dialog.value.role.remarks = "";
    //显示对话框
    dialog.value.visible = true;
}
//实现用户修改/新增操作
const insertAndUpdateUser = async () => {
    //修改操作
    if (dialog.btnText == '更新数据') {
        // console.log(dialog.value.user); //查询是否有值
        let res = await request.put("/role/saveOrUpdate", dialog.value.role);
        //判断新增成功
        if (res.data.success) {
            //1.刷新页面
            findAll();
            //2.显示提示信息
            ElMessage.success("修改成功")
            //4.关闭对话框
            dialog.value.visible = false;
        }
    } else {
        // console.log(dialog.value.user); //查询是否有值
        let res = await request.put("/role/saveOrUpdate", dialog.value.role);
        //判断新增成功
        if (res.data.success) {
            //1.刷新页面
            findAll();
            //2.显示提示信息
            ElMessage.success("修改成功")
            //4.关闭对话框
            dialog.value.visible = false;
        }
    }
}
//实现单个删除
const handleDelete = async (row) => {

    let res = await request.delete(`/role/delectIfNotExistsUser/${row.rid}`);

    if (res.data.success) {
        findAll();
        ElMessage.success("删除成功");
    } else {
        ElMessage.error(res.data.message);
    }
}
//更新角色菜单对话框数据
let updateMenudialog = reactive({
    visible: false,
    title: '更新角色菜单',
    roleId: '',
    menus: [],
    defaultKeys: [],

})
//更新角色菜单按钮
const updateRoleMenuBtn = async (role) => {
    //1,把当前角色数据保存下来
    updateMenudialog.roleId = role.rid;
    //2,查询所有菜单数据
    let res = await request.get('/menu/queryAllofTree');
    //清空数组
    updateMenudialog.defaultKeys = [];
    if (res.data.success) {
        updateMenudialog.menus = res.data.data;
    }
    //设置默认选中的项
    role.menus.map(m => {
        m.children.map(subMenu => {
            //把所有的二级菜单保存到defaultKeys
            updateMenudialog.defaultKeys.push(subMenu.mid);
        })
    })
    //.显示对话框
    updateMenudialog.visible = true;
}
//更新角色菜单的提交按钮
const updateRoleMenus = async()=>{
    //获取当前选中的所有菜单，包括半选中的一级菜单
    //getCheckedNodes返回所有选中的二级菜单
    //getHalfCheckedNodes返回所有选中的一级菜单
    let trees = menuTree.value.getCheckedNodes().concat(menuTree.value.getHalfCheckedNodes());
    //发送请求
    let res =await request.put(`/role/updateMenusByRoleId/${updateMenudialog.roleId}`,trees);
    if(res.data.success){
        ElMessage.success("修改成功")
    }else{
        ElMessage.error(res.data.message);
    }
    //.关闭对话框
    updateMenudialog.visible = false;
}
//根据查询所有角色信息
const findAll = async () => {
    let res = await request.get("/role/findAll");
    if (res.data.success) {
        tableData.roles = res.data.data;
        return true;
    } else {
        return false;
    }
}
//当实例挂载到元素之后触发onMounted
onMounted(() => {
    //1.调用方法实现，查询用户数据
    findAll();
})
</script>